package wy.hanyufang.cn.socket.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wy.hanyufang.cn.socket.SimpleChannelHandlerPool;

/**
 * channel处理实现
 * @author ： wyhanyufang@163.com
 * @time ： 5:39 PM 2021/9/21
 */
public class SimpleSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private  static Logger logger = LoggerFactory.getLogger(SimpleSocketHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        logger.info(".....");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //建立连接
        logger.info("与客户端建立连接...已连接客户端数量：{}",SimpleChannelHandlerPool.size());
        SimpleChannelHandlerPool.channels.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("与客户端断开连接...");
        SimpleChannelHandlerPool.channels.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("接收客户端信息....");
        //首次连接
        if (msg instanceof FullHttpRequest){
            FullHttpRequest fullHttpRequest = (FullHttpRequest)msg ;
            logger.info("客户端首次连接...");
        }
        //正常的客户端文本数据
        else if (msg instanceof TextWebSocketFrame){
            TextWebSocketFrame frame = (TextWebSocketFrame)msg  ;
            logger.info("接收到客户端数据...data:"+frame.text());
        }

        super.channelRead(ctx, msg);
    }
}
